package com.stockz.ui.swing.charting.painter.chart;

import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.List;

import org.springframework.stereotype.Component;

import com.stockz.core.model.Bar;
import com.stockz.ui.swing.charting.util.MathUtil;
import com.stockz.ui.swing.charting.view.StockChartPanel;
import com.stockz.ui.swing.charting.view.StockChartPanelSkin;
import com.stockz.ui.swing.charting.view.StockChartPanelState;

@Component
public class OHLCBarChartPainter implements StockChartPainter {

	public void paint(Graphics2D g, StockChartPanel stockChartPanel, Rectangle rectangle) {
		StockChartPanelSkin stockChartPanelSkin = stockChartPanel.getStockChartPanelSkin();
		StockChartPanelState stockChartPanelState = stockChartPanel.getStockChartPanelState();
		g.setColor(stockChartPanelSkin.getBarColor());
		List<Bar> barList = stockChartPanelState.getBarList();
		
		for(int i = stockChartPanelState.getEndIndex()-1; i >= stockChartPanelState.getStartIndex(); i--){
			Bar bar = barList.get(i);
			int x = MathUtil.fitX(rectangle.x, 
					stockChartPanelState.getTimeUnitSpace(), 
					stockChartPanelState.getEndIndex(), 
					i);
			g.drawLine(
					x,
					MathUtil.fitY(rectangle.y, 
							rectangle.y+rectangle.height, 
							stockChartPanelState.getMinimumPriceVisible(), 
							stockChartPanelState.getMaximumPriceVisible(), 
							bar.getHigh(),
							stockChartPanelState.isSemiLog()),
					x,
					MathUtil.fitY(rectangle.y, 
							rectangle.y+rectangle.height, 
							stockChartPanelState.getMinimumPriceVisible(), 
							stockChartPanelState.getMaximumPriceVisible(), 
							bar.getLow(),
							stockChartPanelState.isSemiLog())
					);
			int openY = MathUtil.fitY(rectangle.y, 
					rectangle.y+rectangle.height, 
					stockChartPanelState.getMinimumPriceVisible(), 
					stockChartPanelState.getMaximumPriceVisible(), 
					bar.getOpen(),
					stockChartPanelState.isSemiLog());
			g.drawLine(
					x-stockChartPanelState.getTimeUnitSpace()/2,
					openY,
					x,
					openY
					);
			int closeY = MathUtil.fitY(rectangle.y, 
					rectangle.y+rectangle.height, 
					stockChartPanelState.getMinimumPriceVisible(), 
					stockChartPanelState.getMaximumPriceVisible(), 
					bar.getClose(),
					stockChartPanelState.isSemiLog());
			g.drawLine(
					x+stockChartPanelState.getTimeUnitSpace()/2,
					closeY,
					x,
					closeY
					);
		}
		
	}

	@Override
	public String toString() {		
		return "Open-High-Low-Close";
	}
	
}
